import {
  Component,
  ChangeDetectionStrategy,
  OnInit,
  OnDestroy,
  ChangeDetectorRef
} from '@angular/core';
import { _HttpClient } from '@delon/theme';
import { zip } from 'rxjs';
import { NzMessageService } from 'ng-zorro-antd';
import { Router } from '@angular/router';
@Component({
  selector: 'business-staff-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.less'],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class BusinessStaffAddComponent implements OnInit, OnDestroy {
  userLoading = false;
  user: any;
  object: any = localStorage['currentData']?JSON.parse(localStorage['currentData']): '';
  constructor(
    private http: _HttpClient,
    private cd: ChangeDetectorRef,
    private msg: NzMessageService,
    private router: Router
  ) {}

  ngOnInit() {
    if(this.object) {
      this.user = {
        nativePlace: this.object.nativePlace,
        department: this.object.department,
        name: this.object.name,
        gender: this.object.gender,
        post: this.object.post,
        status: this.object.status,
        avatar: this.object.avatar,
        birthday: this.object.birthday,
        marriage: this.object.marriage,
        education: this.object.education,
        salary: this.object.salary,
        phoneNumber: this.object.phoneNumber,
        address: this.object.address
      }
    }else{
      this.user = {
        nativePlace: '',
        department: '人事部',
        name: '',
        gender: '男',
        post: '',
        status: '待入职',
        avatar: 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png',
        birthday: new Date(),
        marriage: '是',
        education: '本科',
        salary: '',
        phoneNumber: '',
        address: ''
      }
    }
  }
  save() {
    let obj = this.user
    if(this.object) {
      this.userLoading = true;
      obj['_id'] = this.object._id;
      this.http.patch('api/staff/update/', obj).subscribe((res: any) => {
        this.userLoading = false;
        if(res.success) {
          this.msg.success(`修改成功`);
          // 路由跳转
          this.router.navigate(['/business/staff/list']);
        }else{
          this.msg.error(`部门已存在`);
        }
      }, () => {
        this.msg.error(`网络请求失败`);
      });
    }else {
      this.http.post('api/staff/add/', obj).subscribe((res: any) => {
        this.userLoading = false;
        if(res.success) {
          this.msg.success(`添加成功`);
          // 路由跳转
          this.router.navigate(['/business/staff/list']);
        }else{
          this.msg.error(`员工已存在`);
        }
      }, () => {
        this.msg.error(`网络请求失败`);
      });
    }
  }
  ngOnDestroy() {
    if(this.object) {
      localStorage.removeItem('currentData');
    }
  }
}
